<template>
    <a-modal
        v-model:visible="visible"
        :title="title"
        :on-before-ok="handleBeforeOk"
        @cancel="handleCancel"
    >
        <template #title></template>
        <div>
            <a-form ref="formRef" :model="formData" :rules="formRules">
                <a-form-item field="specName" :label="$t('gui-ge-ming-cheng')">
                    <a-input v-model="formData.specName"></a-input>
                </a-form-item>
                <a-form-item field="specValue" :label="$t('gui-ge-zhi')">
                    <a-input v-model="formData.specValue"></a-input>
                </a-form-item>
                <a-form-item field="sort" :label="$t('pai-xu')">
                    <a-input-number
                        v-model="formData.sort"
                        :precision="0"
                        :min="0"
                        model-event="input"
                    />
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
    import { ref, reactive, PropType } from 'vue';
    import { useI18n } from 'vue-i18n';
    import { addDeviceSpec, editDeviceSpec } from '../service';

    const { t } = useI18n();
    const props = defineProps({
        title: {
            type: String,
            default: undefined,
        },
        type: {
            type: String as PropType<'ADD' | 'EDIT'>,
            default: 'ADD',
        },
    });

    const emit = defineEmits(['submit']);

    const visible = ref(false);
    const formRef = ref();
    const formData = reactive({
        specName: '',
        specValue: '',
        sort: 1,
    });
    const formRules = {
        specName: [
            {
                required: true,
                message: t('qing-shu-ru-gui-ge-ming-cheng'),
            },
        ],
        specValue: [
            {
                required: true,
                message: t('qing-shu-ru-gui-ge-zhi'),
            },
        ],
    };

    function open(data: any) {
        Object.assign(formData, data);
        visible.value = true;
    }

    const handleBeforeOk = async () => {
        const res = await formRef.value.validate();
        if (!res) {
            if (props.type === 'ADD') {
                await addDeviceSpec(formData);
            } else {
                await editDeviceSpec(formData);
            }
            emit('submit');
            formRef.value.resetFields();
            return true;
        }
        return false;
    };

    function handleCancel() {
        formRef.value.resetFields();
        visible.value = false;
    }

    defineExpose({
        open,
    });
</script>
